import { Repository , getRepository } from 'typeorm';
import { validate, ValidationError } from "class-validator";
import { BaseContext } from "koa";
import { Season } from '../entity/season';

export default class SeasonControl {

    public static async saveSeason(season: Array<Season>) {
        const seasonRepository: Repository<Season> = getRepository(Season);
        const errors: ValidationError[] = await validate(season);
        if(errors.length > 0) console.log(errors);
        else await seasonRepository.save(season);
    }

    public static querySeasonAll(): Promise<Array<Season>> {
        return new Promise(async (resolve,reject) => {
            const seasonRepository: Repository<Season> = getRepository(Season);
            let seasons: Season[] = await seasonRepository.find();
            resolve(seasons);
        })
    }

    public static querySeasonByName(name: string): Promise<Season> {
        return new Promise(async (resolve,reject) => {
            const seasonRepository: Repository<Season> = getRepository(Season);
            let season: Season = await seasonRepository.findOne({
                name
            });
            resolve(season);
        })
    }

    public static async getSeasonLists(ctx: BaseContext) {
        try {
            const SeasonRepository: Repository<Season> = getRepository(Season);
            const seasonLists: Array<Season> = await SeasonRepository.find();
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                seasonLists,
            });

        }catch(error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);

        }
    }

    public static async getSeasonByName(ctx: BaseContext) {
        try {
            const SeasonRepository: Repository<Season> = getRepository(Season);
            const seasons: Array<Season> = await SeasonRepository.find({
                name: ctx.query.name
            });
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                seasons,
            });

        }catch(error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);

        }
    }
}